package com.frxuexi.mine

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.mine.entity.User
import com.frxuexi.mine.room.AppDataBase
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class UserViewModel(private val repository: UserRepository) : ViewModel() {

    val channel = Channel<UserIntent>(Channel.UNLIMITED)

    private var _userState = MutableStateFlow<UserState>(UserState.onLoading)
    val userState: StateFlow<UserState>
        get() = _userState

    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect {
                when (it) {
                    is UserIntent.register->{
                        register(it.user)
                    }
                    is UserIntent.login->{
                        login(it.name,it.pass)
                    }
                    else->{

                    }
                }
            }
        }

    }

    private fun login(name: String, pass: String) {
        viewModelScope.launch {
            val user = repository.login(name,pass)
            if(user!=null){
                _userState.value=UserState.onLoginSuccess(user = user)
            }else{
                _userState.value=UserState.onError
            }
        }
    }

    private fun register(user: User) {
        viewModelScope.launch {
            val addUser = repository.addUser(user)
            _userState.value=UserState.onRegisterSuccess
            if(addUser>0){
                _userState.value=UserState.onRegisterSuccess
            }else{
                _userState.value=UserState.onError
            }
        }
    }

}